Socket Programming - I
with Python

Manish Patel

04-June-2023

Available ports

netstat -ano #display listening and established connections
netstat -n #list active tcp
netstat -n -o #ports and pid

INSTALL NBTUTOR

pip install nbtutor
jupyter nbextension install --overwrite --py nbtutor
jupyter nbextension enable --py nbtutor

USAGE

%reload_ext nbtutor #CELL MAGIC

%%nbtutor -r -f #PROG MAGIC

WHICH PORT AM I USING?

import socket

# Get the hostname of the current machine
hostname = socket.gethostname()

# Get the IP address associated with the hostname
ip_address = socket.gethostbyname(hostname)

# Create a dummy socket to get the port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind(('localhost', 0))  # Bind to a random available port
    _, port = s.getsockname()

# Print the IP address and port
print("Hostname:", hostname)
print("IP Address:", ip_address)
print("Port:", port)
Hostname: MANISH-PATEL
IP Address: 192.168.1.2
Port: 61317

ISP DETAILS

import requests

# Make a request to the ip-api.com JSON API
response = requests.get('http://ip-api.com/json')

# Parse the response as JSON
data = response.json()

# Extract ISP information
isp = data.get('isp', 'Unknown')
organization = data.get('org', 'Unknown')
as_number = data.get('as', 'Unknown')
as_name = data.get('asname', 'Unknown')
region = data.get('regionName', 'Unknown')
city = data.get('city', 'Unknown')
country = data.get('country', 'Unknown')
zipcode = data.get('zip', 'Unknown')
latitude = data.get('lat', 'Unknown')
longitude = data.get('lon', 'Unknown')
timezone = data.get('timezone', 'Unknown')

# Print the ISP information
print("ISP:", isp)
print("Organization:", organization)
print("AS Number:", as_number)
print("AS Name:", as_name)
print("Region:", region)
print("City:", city)
print("Country:", country)
print("Zip Code:", zipcode)
print("Latitude:", latitude)
print("Longitude:", longitude)
print("Timezone:", timezone)
ISP: Bharti Airtel
Organization: Bharti Airtel Ltd.
AS Number: AS24560 Bharti Airtel Ltd., Telemedia Services
AS Name: Unknown
Region: Gujarat
City: Ahmedabad
Country: India
Zip Code: 380052
Latitude: 23.0276
Longitude: 72.5871
Timezone: Asia/Kolkata

GET MY IP ADDRESS

import socket

# Create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect to a remote host and port (example: www.google.com, 80)
s.connect(('www.google.com', 80))

# Get the IP address
ip_address = socket.gethostbyname(socket.gethostname())

print("The IP address being used is:", ip_address)

# Close the socket
s.close()
The IP address being used is: 192.168.22.179

WEBSITE IP ADDRESS USING SOCKET

import socket

def get_ip_address(host):
    # Get IP address using gethostbyname()
    ip = socket.gethostbyname(host)
    return ip

def get_ip_address_advanced(host):
    # Get IP address using getaddrinfo()
    addr_info = socket.getaddrinfo(host, 80)
    ip = addr_info[0][4][0]
    return ip

# Example usage
website = "www.google.com"

# Get IP address using gethostbyname()
ip_address = get_ip_address(website)
print("IP address of", website, "is:", ip_address)

# Get IP address using getaddrinfo()
ip_address_advanced = get_ip_address_advanced(website)
print("Advanced IP address of", website, "is:", ip_address_advanced)
IP address of www.google.com is: 142.250.192.132
Advanced IP address of www.google.com is: 2404:6800:4009:829::2004

INTERNET CONNECTION USING SOCKET

import socket

# Define the remote host and port
host = 'www.google.com'
port = 80

# Create a socket object
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect to the remote host
client_socket.connect((host, port))
print("Connected to {}:{}".format(host, port))

# Send data to the server
request = "GET / HTTP/1.1\r\nHost: {}\r\n\r\n".format(host)
client_socket.sendall(request.encode())

# Receive the server's response
response = client_socket.recv(4096)
print("Received response:\n{}".format(response.decode()))

# Close the connection
client_socket.close()
Connected to www.google.com:80
Received response:
HTTP/1.1 200 OK
Date: Thu, 01 Jun 2023 04:45:59 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=ISO-8859-1
Content-Security-Policy-Report-Only: object-src 'none';base-uri 'self';script-src 'nonce-GvF9aTKeVFvl0pcUsr2XTQ' 'strict-dynamic' 'report-sample' 'unsafe-eval' 'unsafe-inline' https: http:;report-uri https://csp.withgoogle.com/csp/gws/other-hp
P3P: CP="This is not a P3P policy! See g.co/p3phelp for more info."
Server: gws
X-XSS-Protection: 0
X-Frame-Options: SAMEORIGIN
Set-Cookie: 1P_JAR=2023-06-01-04; expires=Sat, 01-Jul-2023 04:45:59 GMT; path=/; domain=.google.com; Secure
Set-Cookie: AEC=AUEFqZf6ino26IOgt2V97n8pX7vbmjiOQT4ISjQTc7uBe4dAKwjFc54HYlQ; expires=Tue, 28-Nov-2023 04:45:59 GMT; path=/; domain=.google.com; Secure; HttpOnly; SameSite=lax
Set-Cookie: NID=511=fwqIQkKGLFkFn9Wq6Rq3S2hr8lLjbL414IkilJYFKRpHPwhDI-efTBuamcKxbE6aqgKQLnHn7o_tGeLpxcyOsz7FtnAD8mrO03bxHO2VNBT2wxij57_Rg426ObKN1yTmuSl62pw2pEIFHhkE08f1ya2T-I7CJI5FTDs7R_jivQo; expires=Fri, 01-Dec-2023 04:45:59 GMT; path=/; domain=.google.com; HttpOnly
Accept-Ranges: none
Vary: Accept-Encoding
Transfer-Encoding: chunked

5148
<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en-IN"><head><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><title>Google</title><script nonce="GvF9aTKeVFvl0pcUsr2XTQ">(function(){var _g={kEI:'hyJ4ZPPREJPe1sQPgOuAKA',kEXPI:'0,18168,1341241,6058,207,4804,2316,383,246,5,1129120,1704,1196016,674,380097,16114,28684,22431,1361,12311,17588,4998,17075,38444,2872,2891,562,3577,7615,606,30668,30022,16105,230,1014,1,16916,2652,4,1528,2304,29062,13065,11442,2216,4437,9358,13252,6627,7596,1,39042,2,3110,2,14022,2715,23024,5679,1021,31122,4567,6259,23418,1249,5838,14967,4333,8,7476,445,2,2,1,26632,8155,7381,2,15968,873,7829,11804,7,1922,52238,20198,928,19209,14,82,13332,6874,3370,5007,3787,15173,3881,1522,1494,1536,6110,9706,1804,5221,2513,2738,490,2395,141,308,2047,5159,3537,1859,6689,2172,5252,2992,542,1330,2039,1290,298,1876,309,5468,892,867,2712,1268,170,1129,422,6922,427,505,358,1808,1271,1991,4579,210,538,1644,280,2544,3,894,182,818,2185,1675,943,90,510,1599,3,3,9,859,2541,697,643,221,6,92,44,265,126,1235,680,372,1755,21,1,176,1802,84,5200549,6268,557,51,82,2,5994880,2803271,3311,936,4,19732,1,298,48,6097,45,226,5,17,70,26,5,26,5,1,33,1,3,3,5,3,20723894,3220020,578,2737885,1303679,1964,1007,15665,2894,6250,14715,5174,5125,1405782,253927,23505896,130,84,94,133,2049,4,549,2,258,292,766,1403,1,714,453,678,264,2038,898,194,